package org.jflame.commons.valid;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;

/**
 * 延迟编译的正则表达式
 * 
 * @author charles.zhang
 */
public class LazyPattern extends LazyInitializer<Pattern> {

    private final String regex;
    private final int flags;

    public LazyPattern(String regex) {
        this.regex = regex;
        this.flags = 0;
    }

    public LazyPattern(String regex, int flags) {
        this.regex = regex;
        this.flags = flags;
    }

    @Override
    protected Pattern initialize() throws ConcurrentException {
        return flags > 0 ? Pattern.compile(regex, flags) : Pattern.compile(regex);
    }

    public String getRegex() {
        return regex;
    }

    @Override
    public int hashCode() {
        return Objects.hash(flags, regex);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        LazyPattern other = (LazyPattern) obj;
        return flags == other.flags && Objects.equals(regex, other.regex);
    }

    public boolean isMatch(CharSequence input) {
        if (input == null) {
            return false;
        }
        try {
            return get().matcher(input)
                    .matches();
        } catch (ConcurrentException e) {
            throw new RuntimeException(e.getCause());
        }
    }

    public Matcher matcher(CharSequence input) {
        Objects.requireNonNull(input);
        try {
            return get().matcher(input);
        } catch (ConcurrentException e) {
            throw new RuntimeException(e.getCause());
        }
    }
}
